package com.example.nna.voz;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.nna.main.R;
import com.example.nna.util.Subscribe;
import com.example.nna.util.UserInfo;

public class page2 extends Activity{
	private ListView mMainList;
	private listViewCustom2 adapter;
	private Parser2 mParser;
	private Activity mActivity;
	private Context mContext;
	private ProgressDialog progressDialog;
	private String mUrl;
	private String mForum;
	private UserInfo mUser;
	private TextView m_TextLogin;
	private PaserTask mTask;
	private TextView m_Detail;
	private int stateConenct;
	private AlertDialog.Builder alert;
	private View textEntryView;
	private LayoutInflater factory;
	private EditText edit1 ;
	private EditText edit2 ;
	private TextView text1 ;
	private TextView text2 ; 
	private Subscribe mSubscribe;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page2);
		mSubscribe = new Subscribe(this);
		mMainList = (ListView)findViewById(R.id.page2);
		mActivity = this;
		mContext = this;
		mUser = new UserInfo();
		progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Loading data......");
		mUrl = getIntent().getExtras().getString("url");
		mForum = getIntent().getExtras().getString("forum");
		
		mActivity.setTitle(mForum);
		m_Detail = (TextView)findViewById(R.id.Page2Detail);
		mHandler.obtainMessage(Voz.MSG_PAGE2,mUrl).sendToTarget();
		m_TextLogin = (TextView)findViewById(R.id.Page2Login);
		m_TextLogin.setOnClickListener(mLoginClick);
	}
	
	private OnClickListener mLoginClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			AlertDialog.Builder alert;
		    final View textEntryView;
		    LayoutInflater factory;
		    factory = LayoutInflater.from(mContext);
		    textEntryView = factory.inflate(R.layout.login, null);    
		    final EditText edit1 = (EditText)textEntryView.findViewById(R.id.alert_edit1);
		    final EditText edit2 = (EditText)textEntryView.findViewById(R.id.alert_edit2);
		    final TextView text1 = (TextView)textEntryView.findViewById(R.id.alert_txt1);
		    final TextView text2 = (TextView)textEntryView.findViewById(R.id.alert_txt2);
		    alert = new AlertDialog.Builder(mContext);
		    alert.setView(textEntryView);
		    if(mParser.mUserInfo().isLogin() != true){
			    alert.setTitle("Log in" );
			    text1.setVisibility(View.VISIBLE);
			    text2.setVisibility(View.VISIBLE);
			    edit1.setVisibility(View.VISIBLE);
			    edit2.setVisibility(View.VISIBLE);
			    text1.setText("Username:");
			    text2.setText("Password:");

		    }else{
		    	alert.setTitle("Log out" );
			    text1.setVisibility(View.GONE);
			    text2.setVisibility(View.GONE);
			    edit1.setVisibility(View.GONE);
			    edit2.setVisibility(View.GONE);
		    }
		    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		    	public void onClick(DialogInterface dialog, int whichButton) {
		    		if(mParser.mUserInfo().isLogin() != true){
			    		mUser.add(edit1.getText().toString(), edit2.getText().toString());
			    		mUser.add("hidden1611","thuonghanh");
		    			mHandler.obtainMessage(Voz.MSG_LOGIN,mUrl).sendToTarget();
		    		}else{
		    			mHandler.obtainMessage(Voz.MSG_LOGOUT,mUrl).sendToTarget();
		    		}
		    	}
		    });
		    alert.show();
	   
		}
	};
	private void NextClick(){
		mTask.cancel(true);
		
		if(mParser.Urlnext != null){
			mUrl = mParser.Urlnext;
			mHandler.obtainMessage(Voz.MSG_PAGE2).sendToTarget();
		}else{
			Toast.makeText(mActivity, "Cannot go to Next", Toast.LENGTH_LONG).show();
		}
	}
	
	private void PrevClick(){
		mTask.cancel(true);
		if(mParser.Urlprev != null){
			mUrl = mParser.Urlprev;
			mHandler.obtainMessage(Voz.MSG_PAGE2).sendToTarget();
		}else{
			Toast.makeText(mActivity, "Cannot go to Previous.", Toast.LENGTH_LONG).show();
		}
	}
	private void FirstClick(){

		mTask.cancel(true);
		if(mParser.Urlfirst!=null){
			mUrl = mParser.Urlfirst;
			mHandler.obtainMessage(Voz.MSG_PAGE2).sendToTarget();
		}else Toast.makeText(mActivity, "Cannot go to first! ", Toast.LENGTH_LONG).show();

	}
	private void GotoClick(){

		mTask.cancel(true);
		mHandler.obtainMessage(Voz.MSG_PAGE2).sendToTarget();
	}
	private void LastClick(){

		mTask.cancel(true);
		
		if(mParser.Urllast != null){
			mUrl = mParser.Urllast;
			mHandler.obtainMessage(Voz.MSG_PAGE2).sendToTarget();
		}else{
			Toast.makeText(mActivity, "Cannot go to Last", Toast.LENGTH_LONG).show();
		}
	}
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		// TODO Auto-generated method stub
//		menu.findItem(R.id.menu_subscribe).setVisible(false);
//    	if(mUser.isLogin()){
//    		menu.findItem(R.id.menu_favourite).setVisible(true);
//    	}else{
//    		menu.findItem(R.id.menu_favourite).setVisible(false);
//    	}
		return super.onMenuOpened(featureId, menu);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_parser_html, menu);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
	        case R.id.menu_settings:
		        LayoutInflater factory2 = LayoutInflater.from(mContext);
			    View textEntryView2 = factory2.inflate(R.layout.alertsetting, null); 
			    CheckBox checkbox = (CheckBox)textEntryView2.findViewById(R.id.checkBox1);
			    
			    final Spinner spinner2 = (Spinner)textEntryView2.findViewById(R.id.setting_spinner2);
				List<String> list = new ArrayList<String>();
				list.add("1");
				list.add("5");
				list.add("10");
				list.add("15");
				list.add("30");
				ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext,
					android.R.layout.simple_spinner_item, list);
				dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinner2.setAdapter(dataAdapter);
				spinner2.setSelection(Voz.mNotifTimerSelection);
			    spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
		
					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						Voz.mNotifTimer = Integer.parseInt(arg0.getItemAtPosition(arg2).toString());
						Voz.mNotifTimerSelection = arg2;
					}
		
					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
						
					}
				});
			    
			    if(Voz.mNotifEnable) checkbox.setChecked(true);
			    else 	checkbox.setChecked(false);
			    if(checkbox.isChecked()) Voz.mNotifEnable = true;
			    else Voz.mNotifEnable = false;
			    Builder alert2 = new AlertDialog.Builder(mContext);
			    alert2.setView(textEntryView2);
			    alert2.setTitle("Setting");
			    alert2.show();
		        return true;
//	        case R.id.menu_favourite:
//	        	
//	  			Intent i = new Intent(mContext,pageUserCP.class );
//				startActivity(i);
//	        	return true;  
	        case R.id.menu_font:
	        	LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    	    View layout = inflater.inflate(R.layout.seekbar, null);
	    	    AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(layout);
	    	    AlertDialog alertDialog = builder.create();
	    	    alertDialog.show();
	    	    SeekBar sb = (SeekBar)layout.findViewById(R.id.seek);
	    	    sb.setMax(30);
	    	    sb.setProgress((int)(30*(Voz.mTextSize-Voz.FONTSCALE_MIN)/(Voz.FONTSCALE_MAX-Voz.FONTSCALE_MIN)));
	    	    sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
	    	        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
	    	            //Do something here with new value
	    	        	Voz.mTextSize = (float)((Voz.FONTSCALE_MAX-Voz.FONTSCALE_MIN)/(30-0)*(progress) + Voz.FONTSCALE_MIN);
	      	        	adapter.setSize(Voz.mTextSize);
	    	        	adapter.notifyDataSetChanged();
	    	        }
					@Override
					public void onStartTrackingTouch(SeekBar arg0) {
						// TODO Auto-generated method stub

					}
					@Override
					public void onStopTrackingTouch(SeekBar arg0) {
						// TODO Auto-generated method stub
					}
	    	    });
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	        }
	}
	private void alertDialog(){
	    factory = LayoutInflater.from(mContext);
	    textEntryView = factory.inflate(R.layout.login, null);    
	    edit1 = (EditText)textEntryView.findViewById(R.id.alert_edit1);
	    edit2 = (EditText)textEntryView.findViewById(R.id.alert_edit2);
	    text1 = (TextView)textEntryView.findViewById(R.id.alert_txt1);
	    text2 = (TextView)textEntryView.findViewById(R.id.alert_txt2);
	    alert = new AlertDialog.Builder(mContext);
	    alert.setView(textEntryView);
    }
	private void alertDialogDisconnect(){
    	edit1.setVisibility(View.GONE);
    	edit2.setVisibility(View.GONE);
    	text2.setVisibility(View.GONE);
    	text1.setText("Error Connection");
    }
	 private void alertDialogLogin(){
	    	edit1.setVisibility(View.GONE);
	    	edit2.setVisibility(View.GONE);
	    	text2.setVisibility(View.GONE);
	    	text1.setText("Invalid username or password");
	    }
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.d("nna","Page2Start");
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		//mTask.cancel(true);
		Log.d("nna","Page2Stop");
	}
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		if(mParser.mUserInfo().isLogin()==true){
			m_TextLogin.setText(mParser.mUserInfo().User());
		}else m_TextLogin.setText("Log on");
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.d("nna","Page2Resume");
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mTask.cancel(true);
		Log.d("nna","Page2Detroy");
	}
	private class PaserTask extends AsyncTask<Integer, Void, Void>{

		@Override
		protected Void doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			switch (params[0]) {
			case Voz.PASER_PASER:
				stateConenct = mParser.parser();
				if(stateConenct==-1){
					Log.d("nna", "loi");
				}
				break;
			case Voz.PASER_LOGIN:
				stateConenct=mParser.Login(mUser);
				if(stateConenct==-1){
					Log.d("nna", "loi");
				}
				break;	
			case Voz.PASER_LOGOUT:
				stateConenct= mParser.Logout();
				if(stateConenct==-1){
					Log.d("nna", "loi");
				}
				break;
			case Voz.PASER_SUBSCRIBE:
				mParser.Subscribe("2970371");
				break;
			default:
				break;
			}
			return null;
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			progressDialog.show();
			super.onPreExecute();
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			progressDialog.dismiss();
			m_Detail.setText(mParser.getIndexPage());
			if(mParser.mUserInfo().isLogin()==true){
				m_TextLogin.setText(mParser.mUserInfo().User());
			}else m_TextLogin.setText("Log on");
			
			adapter.notifyDataSetChanged();
			switch (stateConenct) {
			case 0:
				if(mParser.mUserInfo().isLogin()==true){
					m_TextLogin.setText(mParser.mUserInfo().User());
				}else m_TextLogin.setText("Log on");
				for(int i=0;i<mParser.getContain().size();i++){
					if(mSubscribe.isSubscribe(mParser.getContain(i).UrlThread()))
						mParser.getContain(i).setStart(true);
				}
				adapter.notifyDataSetChanged();
				break;
			case -1:
				alertDialog();
				alertDialogDisconnect();
				alert.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
			    	public void onClick(DialogInterface dialog, int whichButton) {
			    		mHandler.obtainMessage(0).sendToTarget();
			    	}
			    });
				alert.show();
				break;
			case -2:
				alertDialog();
				alertDialogLogin();
				alert.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
			    	public void onClick(DialogInterface dialog, int whichButton) {
			    		//mHandler.obtainMessage(MSG_LOGIN).sendToTarget();
			    		m_TextLogin.performClick();
			    	}
			    });
				alert.show();
				break;
			default:
				break;
			}
		}
     }
	 public final Handler mHandler = new Handler(){
	    	@Override
	    	public void handleMessage(Message msg) {
	    		int pos; 
	    		switch (msg.what) {
	    		case Voz.MSG_SUBSCRIBE:
	    			new PaserTask().execute(Voz.PASER_SUBSCRIBE);
	    			break;
	    		case Voz.MSG_GOTO:
	    			switch ((Integer)msg.obj) {
					case 0:	GotoClick();break;
					case 1:	FirstClick();break;
					case 2:	PrevClick(); break;
					case 3:	NextClick();break;
					case 4:	LastClick();break;
					default:break;
					}
	    			break;
	    		 case Voz.MSG_PAGE2:
	    			
	    			if((msg.obj != null) &&  
	    					(msg.obj.toString().contains("vozforums.com") != true)){
	    				pos = Integer.parseInt(msg.obj.toString());
	    				mUrl = "http://vozforums.com/" + mParser.getContain(pos).UrlThread();
	    			}
	    		    mParser = new Parser2(mUrl);
	  		        adapter = new listViewCustom2(mActivity, mHandler, mParser.getContain());
	  		        adapter.setSize(Voz.mTextSize);
	  		        mMainList.setAdapter(adapter);
	  		        mTask = new PaserTask();
	  		        mTask.execute(Voz.PASER_PASER);
	    			 break;
	    		 case Voz.MSG_PAGE3:
	     			Intent i = new Intent(mContext,page3.class );
	     			Bundle extras = new Bundle();
	     			extras.putString("url","http://vozforums.com/"+(String)msg.obj);
	     			extras.putString("forum",mForum);
	     			i.putExtras(extras);
	 				startActivity(i);
//	    			pos = Integer.parseInt(msg.obj.toString());
//	     			Intent i = new Intent(mContext,page3.class );
//	     			Bundle extras = new Bundle();
//	     			extras.putString("url","http://vozforums.com/"+mParser.getContain(pos).UrlThread());
//	     			extras.putString("forum",mForum);
//	     			i.putExtras(extras);
//	 				startActivity(i);
	 		    	break;
	    		 case Voz.MSG_LIKEPAGE:
	    			 extras = new Bundle();
	    			 extras = new Bundle();
	    			 extras.putString("url","http://vozforums.com/"+mSubscribe.getThread((Integer)msg.obj));
				 	 extras.putString("forum","test");
	    			 i = new Intent(mContext,page3.class );
	 				 i.putExtras(extras);
	 				 startActivity(i);
	 				 break;
	    		 case Voz.MSG_LOGIN:
	    		    mTask = new PaserTask();
	 		        mTask.execute(Voz.PASER_LOGIN);
	      			break;
	     		 case Voz.MSG_LOGOUT:
	     			mTask = new PaserTask();
	  		        mTask.execute(Voz.PASER_LOGOUT);
	     			break;
	    		 }
	    	};
	    };
}
